home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / firefox / components / FeedWriter.js < prev    next >
Encoding:
Text File  |  2007-04-03  |  36.7 KB  |  1,095 lines

  1. //@line 40 "/build/buildd/firefox-2.0.0.3+1/browser/components/feeds/src/FeedWriter.js"
  2.  
  3. const Cc = Components.classes;
  4. const Ci = Components.interfaces;
  5. const Cr = Components.results;
  6.  
  7. function LOG(str) {
  8.   var prefB = 
  9.     Cc["@mozilla.org/preferences-service;1"].
  10.     getService(Ci.nsIPrefBranch);
  11.  
  12.   var shouldLog = false;
  13.   try {
  14.     shouldLog = prefB.getBoolPref("feeds.log");
  15.   } 
  16.   catch (ex) {
  17.   }
  18.  
  19.   if (shouldLog)
  20.     dump("*** Feeds: " + str + "\n");
  21. }
  22.  
  23. /**
  24.  * Wrapper function for nsIIOService::newURI.
  25.  * @param aURLSpec
  26.  *        The URL string from which to create an nsIURI.
  27.  * @returns an nsIURI object, or null if the creation of the URI failed.
  28.  */
  29. function makeURI(aURLSpec, aCharset) {
  30.   var ios = Cc["@mozilla.org/network/io-service;1"].
  31.             getService(Ci.nsIIOService);
  32.   try {
  33.     return ios.newURI(aURLSpec, aCharset, null);
  34.   } catch (ex) { }
  35.  
  36.   return null;
  37. }
  38.  
  39. const XML_NS = "http://www.w3.org/XML/1998/namespace"
  40. const HTML_NS = "http://www.w3.org/1999/xhtml";
  41. const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
  42. const AAA_NS = "http://www.w3.org/2005/07/aaa";
  43. const TYPE_MAYBE_FEED = "application/vnd.mozilla.maybe.feed";
  44. const URI_BUNDLE = "chrome://browser/locale/feeds/subscribe.properties";
  45.  
  46. const PREF_SELECTED_APP = "browser.feeds.handlers.application";
  47. const PREF_SELECTED_WEB = "browser.feeds.handlers.webservice";
  48. const PREF_SELECTED_ACTION = "browser.feeds.handler";
  49. const PREF_SELECTED_READER = "browser.feeds.handler.default";
  50. const PREF_SHOW_FIRST_RUN_UI = "browser.feeds.showFirstRunUI";
  51.  
  52. const FW_CLASSID = Components.ID("{49bb6593-3aff-4eb3-a068-2712c28bd58e}");
  53. const FW_CLASSNAME = "Feed Writer";
  54. const FW_CONTRACTID = "@mozilla.org/browser/feeds/result-writer;1";
  55.  
  56. const TITLE_ID = "feedTitleText";
  57. const SUBTITLE_ID = "feedSubtitleText";
  58.  
  59. const ICON_DATAURL_PREFIX = "data:image/x-icon;base64,";
  60.  
  61. function FeedWriter() {
  62. }
  63. FeedWriter.prototype = {
  64.   _getPropertyAsBag: function FW__getPropertyAsBag(container, property) {
  65.     return container.fields.getProperty(property).
  66.                      QueryInterface(Ci.nsIPropertyBag2);
  67.   },
  68.   
  69.   _getPropertyAsString: function FW__getPropertyAsString(container, property) {
  70.     try {
  71.       return container.fields.getPropertyAsAString(property);
  72.     }
  73.     catch (e) {
  74.     }
  75.     return "";
  76.   },
  77.   
  78.   _setContentText: function FW__setContentText(id, text) {
  79.     var element = this._document.getElementById(id);
  80.     while (element.hasChildNodes())
  81.       element.removeChild(element.firstChild);
  82.     element.appendChild(this._document.createTextNode(text));
  83.   },
  84.   
  85.   /**
  86.    * Safely sets the href attribute on an anchor tag, providing the URI 
  87.    * specified can be loaded according to rules. 
  88.    * @param   element
  89.    *          The element to set a URI attribute on
  90.    * @param   attribute
  91.    *          The attribute of the element to set the URI to, e.g. href or src
  92.    * @param   uri
  93.    *          The URI spec to set as the href
  94.    */
  95.   _safeSetURIAttribute: 
  96.   function FW__safeSetURIAttribute(element, attribute, uri) {
  97.     var secman = 
  98.         Cc["@mozilla.org/scriptsecuritymanager;1"].
  99.         getService(Ci.nsIScriptSecurityManager);    
  100.     const flags = Ci.nsIScriptSecurityManager.DISALLOW_SCRIPT_OR_DATA;
  101.     try {
  102.       secman.checkLoadURIStr(this._window.location.href, uri, flags);
  103.       // checkLoadURIStr will throw if the link URI should not be loaded per 
  104.       // the rules specified in |flags|, so we'll never "linkify" the link...
  105.       element.setAttribute(attribute, uri);
  106.     }
  107.     catch (e) {
  108.       // Not allowed to load this link because secman.checkLoadURIStr threw
  109.     }
  110.   },
  111.   
  112.   get _bundle() {
  113.     var sbs = 
  114.         Cc["@mozilla.org/intl/stringbundle;1"].
  115.         getService(Ci.nsIStringBundleService);
  116.     return sbs.createBundle(URI_BUNDLE);
  117.   },
  118.   
  119.   _getFormattedString: function FW__getFormattedString(key, params) {
  120.     return this._bundle.formatStringFromName(key, params, params.length);
  121.   },
  122.   
  123.   _getString: function FW__getString(key) {
  124.     return this._bundle.GetStringFromName(key);
  125.   },
  126.  
  127.   /* Magic helper methods to be used instead of xbl properties */
  128.   _getSelectedItemFromMenulist: function FW__getSelectedItemFromList(aList) {
  129.     var node = aList.firstChild.firstChild;
  130.     while (node) {
  131.       if (node.localName == "menuitem" && node.getAttribute("selected") == "true")
  132.         return node;
  133.  
  134.       node = node.nextSibling;
  135.     }
  136.  
  137.     return null;
  138.   },
  139.  
  140.   _setCheckboxCheckedState: function FW__setCheckboxCheckedState(aCheckbox, aValue) {
  141.     // see checkbox.xml
  142.     var change = (aValue != (aCheckbox.getAttributeNS('', 'checked') == 'true'));
  143.     if (aValue)
  144.       aCheckbox.setAttributeNS('', 'checked', 'true');
  145.     else
  146.       aCheckbox.removeAttributeNS('', 'checked');
  147.  
  148.     if (change) {
  149.       var event = this._document.createEvent('Events');
  150.       event.initEvent('CheckboxStateChange', true, true);
  151.       aCheckbox.dispatchEvent(event);
  152.     }
  153.   },
  154.  
  155.   // For setting and getting the file expando property, we need to keep a
  156.   // reference to an explict XPCNativeWrapper around the associated menuitems
  157.   _selectedApplicationItemWrapped: null,
  158.   get selectedApplicationItemWrapped() {
  159.     if (!this._selectedApplicationItemWrapped) {
  160.       this._selectedApplicationItemWrapped =
  161.         XPCNativeWrapper(this._document.getElementById("selectedAppMenuItem"));
  162.     }
  163.  
  164.     return this._selectedApplicationItemWrapped;
  165.   },
  166.  
  167. //@line 219 "/build/buildd/firefox-2.0.0.3+1/browser/components/feeds/src/FeedWriter.js"
  168.  
  169.   /**
  170.    * Writes the feed title into the preview document.
  171.    * @param   container
  172.    *          The feed container
  173.    */
  174.   _setTitleText: function FW__setTitleText(container) {
  175.     if (container.title) {
  176.       this._setContentText(TITLE_ID, container.title.plainText());
  177.       this._document.title = container.title.plainText();
  178.     }
  179.     
  180.     var feed = container.QueryInterface(Ci.nsIFeed);
  181.     if (feed && feed.subtitle)
  182.       this._setContentText(SUBTITLE_ID, container.subtitle.plainText());
  183.   },
  184.   
  185.   /**
  186.    * Writes the title image into the preview document if one is present.
  187.    * @param   container
  188.    *          The feed container
  189.    */
  190.   _setTitleImage: function FW__setTitleImage(container) {
  191.     try {
  192.       var parts = this._getPropertyAsBag(container, "image");
  193.       
  194.       // Set up the title image (supplied by the feed)
  195.       var feedTitleImage = this._document.getElementById("feedTitleImage");
  196.       this._safeSetURIAttribute(feedTitleImage, "src", 
  197.                                 parts.getPropertyAsAString("url"));
  198.       
  199.       // Set up the title image link
  200.       var feedTitleLink = this._document.getElementById("feedTitleLink");
  201.       
  202.       var titleText = 
  203.         this._getFormattedString("linkTitleTextFormat", 
  204.                                  [parts.getPropertyAsAString("title")]);
  205.       feedTitleLink.setAttribute("title", titleText);
  206.       this._safeSetURIAttribute(feedTitleLink, "href", 
  207.                                 parts.getPropertyAsAString("link"));
  208.  
  209.       // Fix the margin on the main title, so that the image doesn't run over
  210.       // the underline
  211.       var feedTitleText = this._document.getElementById("feedTitleText");
  212.       var titleImageWidth = parseInt(parts.getPropertyAsAString("width")) + 15;
  213.       feedTitleText.style.marginRight = titleImageWidth + "px";
  214.     }
  215.     catch (e) {
  216.       LOG("Failed to set Title Image (this is benign): " + e);
  217.     }
  218.   },
  219.   
  220.   /**
  221.    * Writes all entries contained in the feed.
  222.    * @param   container
  223.    *          The container of entries in the feed
  224.    */
  225.   _writeFeedContent: function FW__writeFeedContent(container) {
  226.     // Build the actual feed content
  227.     var feedContent = this._document.getElementById("feedContent");
  228.     var feed = container.QueryInterface(Ci.nsIFeed);
  229.     
  230.     for (var i = 0; i < feed.items.length; ++i) {
  231.       var entry = feed.items.queryElementAt(i, Ci.nsIFeedEntry);
  232.       entry.QueryInterface(Ci.nsIFeedContainer);
  233.       
  234.       var entryContainer = this._document.createElementNS(HTML_NS, "div");
  235.       entryContainer.className = "entry";
  236.  
  237.       // If the entry has a title, make it a like
  238.       if (entry.title) {
  239.         var a = this._document.createElementNS(HTML_NS, "a");
  240.         a.appendChild(this._document.createTextNode(entry.title.plainText()));
  241.       
  242.         // Entries are not required to have links, so entry.link can be null.
  243.         if (entry.link)
  244.           this._safeSetURIAttribute(a, "href", entry.link.spec);
  245.  
  246.         var title = this._document.createElementNS(HTML_NS, "h3");
  247.         title.appendChild(a);
  248.         entryContainer.appendChild(title);
  249.       }
  250.  
  251.       var body = this._document.createElementNS(HTML_NS, "p");
  252.       var summary = entry.summary || entry.content;
  253.       var docFragment = null;
  254.       if (summary) {
  255.  
  256.         if (summary.base)
  257.           body.setAttributeNS(XML_NS, "base", summary.base.spec);
  258.         else
  259.           LOG("no base?");
  260.         docFragment = summary.createDocumentFragment(body);
  261.         body.appendChild(docFragment);
  262.  
  263.         // If the entry doesn't have a title, append a # permalink
  264.         // See http://scripting.com/rss.xml for an example
  265.         if (!entry.title && entry.link) {
  266.           var a = this._document.createElementNS(HTML_NS, "a");
  267.           a.appendChild(this._document.createTextNode("#"));
  268.           this._safeSetURIAttribute(a, "href", entry.link.spec);
  269.           body.appendChild(this._document.createTextNode(" "));
  270.           body.appendChild(a);
  271.         }
  272.  
  273.       }
  274.       body.className = "feedEntryContent";
  275.       entryContainer.appendChild(body);
  276.       feedContent.appendChild(entryContainer);
  277.     }
  278.   },
  279.   
  280.   /**
  281.    * Gets a valid nsIFeedContainer object from the parsed nsIFeedResult.
  282.    * Displays error information if there was one.
  283.    * @param   result
  284.    *          The parsed feed result
  285.    * @returns A valid nsIFeedContainer object containing the contents of
  286.    *          the feed.
  287.    */
  288.   _getContainer: function FW__getContainer(result) {
  289.     var feedService = 
  290.         Cc["@mozilla.org/browser/feeds/result-service;1"].
  291.         getService(Ci.nsIFeedResultService);
  292.  
  293.     try {
  294.       var result = 
  295.         feedService.getFeedResult(this._getOriginalURI(this._window));
  296.     }
  297.     catch (e) {
  298.       LOG("Subscribe Preview: feed not available?!");
  299.     }
  300.     
  301.     if (result.bozo) {
  302.       LOG("Subscribe Preview: feed result is bozo?!");
  303.     }
  304.  
  305.     try {
  306.       var container = result.doc;
  307.       container.title;
  308.     }
  309.     catch (e) {
  310.       LOG("Subscribe Preview: An error occurred in parsing! Fortunately, you can still subscribe...");
  311.       var feedError = this._document.getElementById("feedError");
  312.       feedError.removeAttribute("style");
  313.       var feedBody = this._document.getElementById("feedBody");
  314.       feedBody.setAttribute("style", "display:none;");
  315.       this._setContentText("errorCode", e);
  316.       return null;
  317.     }
  318.     return container;
  319.   },
  320.   
  321.   /**
  322.    * Get the human-readable display name of a file. This could be the 
  323.    * application name.
  324.    * @param   file
  325.    *          A nsIFile to look up the name of
  326.    * @returns The display name of the application represented by the file.
  327.    */
  328.   _getFileDisplayName: function FW__getFileDisplayName(file) {
  329. //@line 398 "/build/buildd/firefox-2.0.0.3+1/browser/components/feeds/src/FeedWriter.js"
  330.     var ios = 
  331.         Cc["@mozilla.org/network/io-service;1"].
  332.         getService(Ci.nsIIOService);
  333.     var url = ios.newFileURI(file).QueryInterface(Ci.nsIURL);
  334.     return url.fileName;
  335.   },
  336.  
  337.   /**
  338.    * Get moz-icon url for a file
  339.    * @param   file
  340.    *          A nsIFile to look up the name of
  341.    * @returns moz-icon url of the given file as a string
  342.    */
  343.   _getFileIconURL: function FW__getFileIconURL(file) {
  344.     var ios = Cc["@mozilla.org/network/io-service;1"].
  345.               getService(Components.interfaces.nsIIOService);
  346.     var fph = ios.getProtocolHandler("file")
  347.                  .QueryInterface(Ci.nsIFileProtocolHandler);
  348.     var urlSpec = fph.getURLSpecFromFile(file);
  349.     return "moz-icon://" + urlSpec + "?size=16";
  350.   },
  351.  
  352.   /**
  353.    * Helper method to set the selected application and system default
  354.    * reader menuitems details from a file object
  355.    *   @param aMenuItem
  356.    *          The menuitem on which the attributes should be set
  357.    *   @param aFile
  358.    *          the menuitem associated file object
  359.    */
  360.   _initMenuItemWithFile: function(aMenuItem, aFile) {
  361.     var label = this._getFileDisplayName(aFile);
  362.     aMenuItem.setAttribute("label", label);
  363.     aMenuItem.setAttribute("src",
  364.                           this._getFileIconURL(aFile));
  365.     aMenuItem.setAttribute("handlerType", "client");
  366.     aMenuItem.file = aFile;
  367.  
  368.     // a11y
  369.     aMenuItem.setAttribute("title", label);
  370.   },
  371.  
  372.   /**
  373.    * Displays a prompt from which the user may choose a (client) feed reader.
  374.    * @return - true if a feed reader was selected, false otherwise.
  375.    */
  376.   _chooseClientApp: function FW__chooseClientApp() {
  377.     try {
  378.       var fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
  379.       fp.init(this._window,
  380.               this._getString("chooseApplicationDialogTitle"),
  381.               Ci.nsIFilePicker.modeOpen);
  382.       fp.appendFilters(Ci.nsIFilePicker.filterApps);
  383.  
  384.       if (fp.show() == Ci.nsIFilePicker.returnOK) {
  385.         var selectedApp = fp.file;
  386.         if (selectedApp) {
  387.           // XXXben - we need to compare this with the running instance executable
  388.           //          just don't know how to do that via script...
  389.           // XXXmano TBD: can probably add this to nsIShellService
  390. //@line 464 "/build/buildd/firefox-2.0.0.3+1/browser/components/feeds/src/FeedWriter.js"
  391.           if (fp.file.leafName != "firefox-bin") {
  392. //@line 467 "/build/buildd/firefox-2.0.0.3+1/browser/components/feeds/src/FeedWriter.js"
  393.             var selectedAppMenuItem = this.selectedApplicationItemWrapped;
  394.             this._initMenuItemWithFile(selectedAppMenuItem, selectedApp);
  395.  
  396.             // Show and select the selected application menuitem
  397.             selectedAppMenuItem.hidden = false;
  398.             selectedAppMenuItem.doCommand();
  399.             return true;
  400.           }
  401.         }
  402.       }
  403.     }
  404.     catch(ex) { }
  405.  
  406.     return false;
  407.   },
  408.  
  409.   _setAlwaysUseCheckedState: function FW__setAlwaysUseCheckedState() {
  410.     var checkbox = this._document.getElementById("alwaysUse");
  411.     if (checkbox) {
  412.       var alwaysUse = false;
  413.       try {
  414.         var prefs = Cc["@mozilla.org/preferences-service;1"].
  415.                     getService(Ci.nsIPrefBranch);
  416.         if (prefs.getCharPref(PREF_SELECTED_ACTION) != "ask")
  417.           alwaysUse = true;
  418.       }
  419.       catch(ex) { }
  420.       this._setCheckboxCheckedState(checkbox, alwaysUse);
  421.     }
  422.   },
  423.  
  424.   _setAlwaysUseLabel: function FW__setAlwaysUseLabel() {
  425.     var checkbox = this._document.getElementById("alwaysUse");
  426.     if (checkbox) {
  427.       var handlersMenuList = this._document.getElementById("handlersMenuList");
  428.       if (handlersMenuList) {
  429.         var handlerName = this._getSelectedItemFromMenulist(handlersMenuList)
  430.                               .getAttribute("label");
  431.         var label = this._getFormattedString("alwaysUse", [handlerName]);
  432.         checkbox.setAttribute("label", label);
  433.  
  434.         // Needed for a11y
  435.         checkbox.setAttribute("title", label);
  436.       }
  437.     }
  438.   },
  439.  
  440.   /**
  441.    * See nsIDOMEventListener
  442.    */
  443.   handleEvent: function(event) {
  444.     // see comments in the write method
  445.     event = new XPCNativeWrapper(event);
  446.     if (event.target.ownerDocument != this._document) {
  447.       LOG("FeedWriter.handleEvent: Someone passed the feed writer as a listener to the events of another document!");
  448.       return;
  449.     }
  450.  
  451.     switch (event.type) {
  452.       case "command" : {
  453.         switch (event.target.id) {
  454.           case "subscribeButton":
  455.             this.subscribe();
  456.             break;
  457.           case "chooseApplicationMenuItem":
  458.             // For keyboard-only users, we only show the file picker once the 
  459.             // subscribe button is pressed. See click event handling for the
  460.             // mouse-case.
  461.             break;
  462.           default:
  463.             event.target.parentNode.parentNode.setAttributeNS
  464.               (AAA_NS, "valuenow", event.target.getAttribute("label"));
  465.  
  466.             this._setAlwaysUseLabel();
  467.         }
  468.         break;
  469.       }
  470.       case "click": {
  471.         if (event.target.id == "chooseApplicationMenuItem") {
  472.           if (!this._chooseClientApp()) {
  473.             // Select the (per-prefs) selected handler if no application was selected
  474.             this._setSelectedHandler();
  475.           }
  476.         }
  477.       }
  478.       case "CheckboxStateChange": {
  479.         // Needed for a11y
  480.         var checkbox = this._document.getElementById("alwaysUse");
  481.         if (checkbox.getAttributeNS("", "checked") == "true")
  482.           checkbox.setAttributeNS(AAA_NS, "checked", "true");
  483.         else
  484.           checkbox.setAttributeNS(AAA_NS, "checked", "false");
  485.        }
  486.     }
  487.   },
  488.  
  489.   _setSelectedHandler: function FW__setSelectedHandler() {
  490.     var prefs =   
  491.         Cc["@mozilla.org/preferences-service;1"].
  492.         getService(Ci.nsIPrefBranch);
  493.  
  494.     var handler = "bookmarks";
  495.     try {
  496.       handler = prefs.getCharPref(PREF_SELECTED_READER);
  497.     }
  498.     catch (ex) { }
  499.     
  500.     switch (handler) {
  501.       case "web": {
  502.         var handlersMenuList = this._document.getElementById("handlersMenuList");
  503.         if (handlersMenuList) {
  504.           var url = prefs.getCharPref(PREF_SELECTED_WEB);
  505.           var handlers =
  506.             handlersMenuList.getElementsByAttribute("webhandlerurl", url);
  507.           if (handlers.length == 0) {
  508.             LOG("FeedWriter._setSelectedHandler: selected web handler isn't in the menulist")
  509.             return;
  510.           }
  511.  
  512.           handlers[0].doCommand();
  513.         }
  514.         break;
  515.       }
  516.       case "client": {
  517.         var selectedAppMenuItem = this.selectedApplicationItemWrapped;
  518.         if (selectedAppMenuItem) {
  519.           try {
  520.             var selectedApp = prefs.getComplexValue(PREF_SELECTED_APP,
  521.                                                     Ci.nsILocalFile);
  522.           } catch(ex) { }
  523.  
  524.           if (selectedApp) {
  525.             this._initMenuItemWithFile(selectedAppMenuItem, selectedApp);
  526.             selectedAppMenuItem.hidden = false;
  527.             selectedAppMenuItem.doCommand();
  528.  
  529. //@line 612 "/build/buildd/firefox-2.0.0.3+1/browser/components/feeds/src/FeedWriter.js"
  530.             break;
  531.           }
  532.         }
  533.       }
  534.       case "bookmarks":
  535.       default: {
  536.         var liveBookmarksMenuItem =
  537.           this._document.getElementById("liveBookmarksMenuItem");
  538.         if (liveBookmarksMenuItem)
  539.           liveBookmarksMenuItem.doCommand();
  540.       } 
  541.     }
  542.   },
  543.  
  544.   _initSubscriptionUI: function FW__initSubscriptionUI() {
  545.     var handlersMenuPopup =
  546.       this._document.getElementById("handlersMenuPopup");
  547.     if (!handlersMenuPopup)
  548.       return;
  549.  
  550.     // Last-selected application
  551.     var selectedApp;
  552.     menuItem = this._document.createElementNS(XUL_NS, "menuitem");
  553.     menuItem.id = "selectedAppMenuItem";
  554.     menuItem.className = "menuitem-iconic";
  555.     handlersMenuPopup.appendChild(menuItem);
  556.  
  557.     var selectedApplicationItem = this.selectedApplicationItemWrapped;
  558.     // a11y
  559.     selectedApplicationItem.setAttributeNS("http://www.w3.org/TR/xhtml2",
  560.                                            "role", "wairole:listitem");
  561.     selectedApplicationItem.setAttributeNS(AAA_NS, "selected", "false");
  562.     try {
  563.       var prefs = Cc["@mozilla.org/preferences-service;1"].
  564.                   getService(Ci.nsIPrefBranch);
  565.       selectedApp = prefs.getComplexValue(PREF_SELECTED_APP,
  566.                                           Ci.nsILocalFile);
  567.       if (selectedApp.exists())
  568.         this._initMenuItemWithFile(selectedApplicationItem, selectedApp);
  569.       else {
  570.         // Hide the menuitem if the last selected application doesn't exist
  571.         selectedApplicationItem.hidden = true;
  572.       }
  573.     }
  574.     catch(ex) {
  575.       // Hide the menuitem until an application is selected
  576.       selectedApplicationItem.hidden = true;
  577.     }
  578.  
  579. //@line 707 "/build/buildd/firefox-2.0.0.3+1/browser/components/feeds/src/FeedWriter.js"
  580.  
  581.     // "Choose Application..." menuitem
  582.     menuItem = this._document.createElementNS(XUL_NS, "menuitem");
  583.     menuItem.id = "chooseApplicationMenuItem";
  584.  
  585.     var chooseAppItemLabel = this._getString("chooseApplicationMenuItem");
  586.     menuItem.setAttribute("label", chooseAppItemLabel);
  587.     // a11y
  588.     menuItem.setAttributeNS("http://www.w3.org/TR/xhtml2",
  589.                             "role", "wairole:listitem");
  590.     menuItem.setAttribute("title", chooseAppItemLabel);
  591.     menuItem.addEventListener("click", this, false);
  592.  
  593.     handlersMenuPopup.appendChild(menuItem);
  594.  
  595.     // separator
  596.     handlersMenuPopup.appendChild(this._document.createElementNS(XUL_NS,
  597.                                   "menuseparator"));
  598.  
  599.     // List of web handlers
  600.     var wccr = 
  601.       Cc["@mozilla.org/embeddor.implemented/web-content-handler-registrar;1"].
  602.       getService(Ci.nsIWebContentConverterService);
  603.     var handlers = wccr.getContentHandlers(TYPE_MAYBE_FEED, {});
  604.     if (handlers.length != 0) {
  605.       for (var i = 0; i < handlers.length; ++i) {
  606.         menuItem = this._document.createElementNS(XUL_NS, "menuitem");
  607.         menuItem.className = "menuitem-iconic";
  608.         menuItem.setAttribute("label", handlers[i].name);
  609.         menuItem.setAttribute("handlerType", "web");
  610.         menuItem.setAttribute("webhandlerurl", handlers[i].uri);
  611.  
  612.         // a11y
  613.         menuItem.setAttribute("title", handlers[i].name);
  614.         menuItem.setAttributeNS("http://www.w3.org/TR/xhtml2",
  615.                                 "role", "wairole:listitem");
  616.         handlersMenuPopup.appendChild(menuItem);
  617.  
  618.         // For privacy reasons we cannot set the image attribute directly
  619.         // to the icon url, see Bug 358878
  620.         var uri = makeURI(handlers[i].uri);
  621.         if (uri && /^https?/.test(uri.scheme))
  622.           new iconDataURIGenerator(uri.prePath + "/favicon.ico", menuItem)
  623.       }
  624.     }
  625.  
  626.     // We update the "Always use.." checkbox label whenever the selected item
  627.     // in the list is changed
  628.     handlersMenuPopup.addEventListener("command", this, false);
  629.     this._setSelectedHandler();
  630.  
  631.     // "Always use..." checkbox initial state
  632.     this._setAlwaysUseLabel();
  633.     this._setAlwaysUseCheckedState();
  634.  
  635.     // Syncs xul:checked with aaa:checked, needed for a11y
  636.     var checkbox = this._document.getElementById("alwaysUse");
  637.     checkbox.addEventListener("CheckboxStateChange", this, false);
  638.  
  639.     // Set up the "Subscribe Now" button
  640.     this._document
  641.         .getElementById("subscribeButton")
  642.         .addEventListener("command", this, false);
  643.     
  644.     // first-run ui
  645.     var showFirstRunUI = true;
  646.     try {
  647.       showFirstRunUI = prefs.getBoolPref(PREF_SHOW_FIRST_RUN_UI);
  648.     }
  649.     catch (ex) { }
  650.     if (showFirstRunUI) {
  651.       var feedHeader = this._document.getElementById("feedHeader");
  652.       if (feedHeader)
  653.         feedHeader.setAttribute("firstrun", "true");
  654.  
  655.       prefs.setBoolPref(PREF_SHOW_FIRST_RUN_UI, false);
  656.     }
  657.   },
  658.  
  659.   /**
  660.    * Returns the original URI object of the feed and ensures that this
  661.    * component is only ever invoked from the preview document.  
  662.    * @param window 
  663.    *        The window of the document invoking the BrowserFeedWriter
  664.    */
  665.   _getOriginalURI: function FW__getOriginalURI(window) {  
  666.     var chan = 
  667.         window.QueryInterface(Ci.nsIInterfaceRequestor).
  668.         getInterface(Ci.nsIWebNavigation).
  669.         QueryInterface(Ci.nsIDocShell_MOZILLA_1_8_BRANCH).
  670.         currentDocumentChannel;
  671.     const SUBSCRIBE_PAGE_URI = "chrome://browser/content/feeds/subscribe.xhtml";
  672.     var uri = Cc["@mozilla.org/network/io-service;1"].
  673.               getService(Ci.nsIIOService).
  674.               newURI(SUBSCRIBE_PAGE_URI, "", null);
  675.     var resolvedURI = Cc["@mozilla.org/chrome/chrome-registry;1"].
  676.                       getService(Ci.nsIChromeRegistry).
  677.                       convertChromeURL(uri);
  678.  
  679.     if (resolvedURI.equals(chan.URI))
  680.       return chan.originalURI;
  681.     else
  682.       return null;
  683.   },
  684.  
  685.   _window: null,
  686.   _document: null,
  687.   _feedURI: null,
  688.  
  689.   /**
  690.    * See nsIFeedWriter
  691.    */
  692.   write: function FW_write(window) {
  693.     // Explicitly wrap |window| in an XPCNativeWrapper to make sure
  694.     // it's a real native object! This will throw an exception if we
  695.     // get a non-native object.
  696.     window = new XPCNativeWrapper(window);
  697.  
  698.     this._feedURI = this._getOriginalURI(window);
  699.      if (!this._feedURI)
  700.       return;
  701.     try {
  702.       this._window = window;
  703.       this._document = window.document;
  704.         
  705.       LOG("Subscribe Preview: feed uri = " + this._window.location.href);
  706.        
  707.       // Set up the displayed handler
  708.       this._initSubscriptionUI();
  709.       var prefs =   
  710.       Cc["@mozilla.org/preferences-service;1"].
  711.       getService(Ci.nsIPrefBranch2);
  712.       prefs.addObserver(PREF_SELECTED_ACTION, this, false);
  713.       prefs.addObserver(PREF_SELECTED_READER, this, false);
  714.       prefs.addObserver(PREF_SELECTED_APP, this, false);
  715.       
  716.        // Set up the feed content
  717.       var container = this._getContainer();
  718.       if (!container)
  719.         return;
  720.       
  721.       this._setTitleText(container);
  722.       
  723.       this._setTitleImage(container);
  724.       
  725.       this._writeFeedContent(container);
  726.     }
  727.     finally {
  728.       this._removeFeedFromCache();
  729.     }
  730.   },
  731.   
  732.   /**
  733.    * See nsIFeedWriter
  734.    */
  735.   close: function FW_close() {
  736.     this._document = null;
  737.     this._window = null;
  738.     var prefs =   
  739.         Cc["@mozilla.org/preferences-service;1"].
  740.         getService(Ci.nsIPrefBranch2);
  741.     prefs.removeObserver(PREF_SELECTED_ACTION, this);
  742.     prefs.removeObserver(PREF_SELECTED_READER, this);
  743.     prefs.removeObserver(PREF_SELECTED_WEB, this);
  744.     prefs.removeObserver(PREF_SELECTED_APP, this);
  745.     this._removeFeedFromCache();
  746.   },
  747.       
  748.   _removeFeedFromCache: function FW__removeFeedFromCache() {
  749.     if (this._feedURI) {
  750.       var feedService = 
  751.           Cc["@mozilla.org/browser/feeds/result-service;1"].
  752.           getService(Ci.nsIFeedResultService);
  753.       feedService.removeFeedResult(this._feedURI);
  754.       this._feedURI = null;
  755.     }
  756.   },  
  757.   
  758.   subscribe: function FW_subscribe() {
  759.     // Subscribe to the feed using the selected handler and save prefs
  760.     var prefs =   
  761.         Cc["@mozilla.org/preferences-service;1"].
  762.         getService(Ci.nsIPrefBranch);
  763.     var defaultHandler = "reader";
  764.     var useAsDefault = this._document.getElementById("alwaysUse")
  765.                                      .getAttribute("checked");
  766.  
  767.     var selectedItem =
  768.       this._getSelectedItemFromMenulist(this._document.getElementById("handlersMenuList"));
  769.  
  770.     // Show the file picker before subscribing if the
  771.     // choose application menuitem was choosen using the keyboard
  772.     if (selectedItem.id == "chooseApplicationMenuItem") {
  773.       if (!this._chooseClientApp())
  774.         return;
  775.       
  776.       selectedItem = this._getSelectedItemFromMenulist(this._document.getElementById("handlersMenuList"));
  777.     }
  778.  
  779.     if (selectedItem.hasAttribute("webhandlerurl")) {
  780.       var webURI = selectedItem.getAttribute("webhandlerurl");
  781.       prefs.setCharPref(PREF_SELECTED_READER, "web");
  782.       prefs.setCharPref(PREF_SELECTED_WEB, webURI);
  783.  
  784.       var wccr = 
  785.         Cc["@mozilla.org/embeddor.implemented/web-content-handler-registrar;1"].
  786.         getService(Ci.nsIWebContentConverterService);
  787.       var handler = wccr.getWebContentHandlerByURI(TYPE_MAYBE_FEED, webURI);
  788.       if (handler) {
  789.         if (useAsDefault)
  790.           wccr.setAutoHandler(TYPE_MAYBE_FEED, handler);
  791.  
  792.         this._window.location.href =
  793.           handler.getHandlerURI(this._window.location.href);
  794.       }
  795.     }
  796.     else {
  797.       switch (selectedItem.id) {
  798.         case "selectedAppMenuItem":
  799.           prefs.setCharPref(PREF_SELECTED_READER, "client");
  800.           prefs.setComplexValue(PREF_SELECTED_APP, Ci.nsILocalFile, 
  801.                                 this.selectedApplicationItemWrapped.file);
  802.           break;
  803. //@line 937 "/build/buildd/firefox-2.0.0.3+1/browser/components/feeds/src/FeedWriter.js"
  804.         case "liveBookmarksMenuItem":
  805.           defaultHandler = "bookmarks";
  806.           prefs.setCharPref(PREF_SELECTED_READER, "bookmarks");
  807.           break;
  808.       }
  809.       var feedService = Cc["@mozilla.org/browser/feeds/result-service;1"].
  810.                         getService(Ci.nsIFeedResultService);
  811.  
  812.       // Pull the title and subtitle out of the document
  813.       var feedTitle = this._document.getElementById(TITLE_ID).textContent;
  814.       var feedSubtitle =
  815.         this._document.getElementById(SUBTITLE_ID).textContent;
  816.       feedService.addToClientReader(this._window.location.href,
  817.                                     feedTitle, feedSubtitle);
  818.     }
  819.  
  820.     // If "Always use..." is checked, we should set PREF_SELECTED_ACTION
  821.     // to either "reader" (If a web reader or if an application is selected),
  822.     // or to "bookmarks" (if the live bookmarks option is selected).
  823.     // Otherwise, we should set it to "ask"
  824.     if (useAsDefault)
  825.       prefs.setCharPref(PREF_SELECTED_ACTION, defaultHandler);
  826.     else
  827.       prefs.setCharPref(PREF_SELECTED_ACTION, "ask");
  828.   },
  829.   
  830.   /**
  831.    * See nsIObserver
  832.    */
  833.   observe: function FW_observe(subject, topic, data) {
  834.     if (!this._window) {
  835.       // this._window is null unless this.write was called with a trusted
  836.       // window object.
  837.       return;
  838.     }
  839.  
  840.     if (topic == "nsPref:changed") {
  841.       switch (data) {
  842.         case PREF_SELECTED_READER:
  843.         case PREF_SELECTED_WEB:
  844.         case PREF_SELECTED_APP:
  845.           this._setSelectedHandler();
  846.           break;
  847.         case PREF_SELECTED_ACTION:
  848.           this._setAlwaysUseCheckedState();
  849.       }
  850.     } 
  851.   },  
  852.   
  853.   /**
  854.    * See nsIClassInfo
  855.    */
  856.   getInterfaces: function WCCR_getInterfaces(countRef) {
  857.     var interfaces = 
  858.         [Ci.nsIFeedWriter, Ci.nsIClassInfo, Ci.nsISupports];
  859.     countRef.value = interfaces.length;
  860.     return interfaces;
  861.   },
  862.   getHelperForLanguage: function WCCR_getHelperForLanguage(language) {
  863.     return null;
  864.   },
  865.   contractID: FW_CONTRACTID,
  866.   classDescription: FW_CLASSNAME,
  867.   classID: FW_CLASSID,
  868.   implementationLanguage: Ci.nsIProgrammingLanguage.JAVASCRIPT,
  869.   flags: Ci.nsIClassInfo.DOM_OBJECT,
  870.  
  871.   QueryInterface: function FW_QueryInterface(iid) {
  872.     if (iid.equals(Ci.nsIFeedWriter) ||
  873.         iid.equals(Ci.nsIClassInfo) ||
  874.         iid.equals(Ci.nsIDOMEventListener) ||
  875.         iid.equals(Ci.nsIObserver) ||
  876.         iid.equals(Ci.nsISupports))
  877.       return this;
  878.     throw Cr.NS_ERROR_NO_INTERFACE;
  879.   }
  880. };
  881.  
  882. function iconDataURIGenerator(aURISpec, aElement) {
  883.   var ios = Cc["@mozilla.org/network/io-service;1"].
  884.             getService(Ci.nsIIOService);
  885.   var chan = ios.newChannelFromURI(makeURI(aURISpec));
  886.   chan.notificationCallbacks = this;
  887.   chan.asyncOpen(this, null);
  888.  
  889.   this._channel = chan;
  890.   this._bytes = [];
  891.   this._element = aElement;
  892. }
  893. iconDataURIGenerator.prototype = {
  894.   _channel: null,
  895.   _countRead: 0,
  896.   _stream: null,
  897.  
  898.   QueryInterface: function FW_IDUG_loadQI(aIID) {
  899.     if (aIID.equals(Ci.nsISupports)           ||
  900.         aIID.equals(Ci.nsIRequestObserver)    ||
  901.         aIID.equals(Ci.nsIStreamListener)     ||
  902.         aIID.equals(Ci.nsIChannelEventSink)   ||
  903.         aIID.equals(Ci.nsIInterfaceRequestor) ||
  904.         aIID.equals(Ci.nsIBadCertListener)    ||
  905.         // See bug 358878 comment 11
  906.         aIID.equals(Ci.nsIPrompt)             ||
  907.         // See FIXME comment below
  908.         aIID.equals(Ci.nsIHttpEventSink)      ||
  909.         aIID.equals(Ci.nsIProgressEventSink)  ||
  910.         false)
  911.       return this;
  912.  
  913.     throw Cr.NS_ERROR_NO_INTERFACE;
  914.   },
  915.  
  916.   // nsIRequestObserver
  917.   onStartRequest: function FW_IDUG_loadStartR(aRequest, aContext) {
  918.     this._stream = Cc["@mozilla.org/binaryinputstream;1"].
  919.                    createInstance(Ci.nsIBinaryInputStream);
  920.   },
  921.  
  922.   onStopRequest: function FW_IDUG_loadStopR(aRequest, aContext, aStatusCode) {
  923.     var requestFailed = !Components.isSuccessCode(aStatusCode);
  924.     if (!requestFailed && (aRequest instanceof Ci.nsIHttpChannel))
  925.       requestFailed = !aRequest.requestSucceeded;
  926.  
  927.     if (!requestFailed && this._countRead != 0) {
  928.       var str = String.fromCharCode.apply(null, this._bytes);
  929.       try {
  930.         var dataURI = ICON_DATAURL_PREFIX +
  931.                       this._element.ownerDocument.defaultView.btoa(str);
  932.         this._element.setAttribute("src", dataURI);
  933.         if (this._element.getAttribute("selected") == "true")
  934.           this._element.parentNode.parentNode.setAttribute("src", dataURI);
  935.       }
  936.       catch(ex) {}
  937.     }
  938.     this._channel = null;
  939.     this._element  = null;
  940.   },
  941.  
  942.   // nsIStreamListener
  943.   onDataAvailable: function FW_IDUG_loadDAvailable(aRequest, aContext,
  944.                                                    aInputStream, aOffset,
  945.                                                    aCount) {
  946.     this._stream.setInputStream(aInputStream);
  947.  
  948.     // Get a byte array of the data
  949.     this._bytes = this._bytes.concat(this._stream.readByteArray(aCount));
  950.     this._countRead += aCount;
  951.   },
  952.  
  953.   // nsIChannelEventSink
  954.   onChannelRedirect: function FW_IDUG_loadCRedirect(aOldChannel, aNewChannel,
  955.                                                     aFlags) {
  956.     this._channel = aNewChannel;
  957.   },
  958.  
  959.   // nsIInterfaceRequestor
  960.   getInterface: function FW_IDUG_load_GI(aIID) {
  961.     return this.QueryInterface(aIID);
  962.   },
  963.  
  964.   // nsIBadCertListener
  965.   confirmUnknownIssuer: function FW_IDUG_load_CUI(aSocketInfo, aCert,
  966.                                                   aCertAddType) {
  967.     return false;
  968.   },
  969.  
  970.   confirmMismatchDomain: function FW_IDUG_load_CMD(aSocketInfo, aTargetURL,
  971.                                                    aCert) {
  972.     return false;
  973.   },
  974.  
  975.   confirmCertExpired: function FW_IDUG_load_CCE(aSocketInfo, aCert) {
  976.     return false;
  977.   },
  978.  
  979.   notifyCrlNextupdate: function FW_IDUG_load_NCN(aSocketInfo, aTargetURL, aCert) {
  980.   },
  981.  
  982.   // FIXME: bug 253127
  983.   // nsIHttpEventSink
  984.   onRedirect: function (aChannel, aNewChannel) { },
  985.   // nsIProgressEventSink
  986.   onProgress: function (aRequest, aContext, aProgress, aProgressMax) { },
  987.   onStatus: function (aRequest, aContext, aStatus, aStatusArg) { }
  988. };
  989.  
  990. var Module = {
  991.   QueryInterface: function M_QueryInterface(iid) {
  992.     if (iid.equals(Ci.nsIModule) ||
  993.         iid.equals(Ci.nsISupports))
  994.       return this;
  995.     throw Cr.NS_ERROR_NO_INTERFACE;
  996.   },
  997.   
  998.   getClassObject: function M_getClassObject(cm, cid, iid) {
  999.     if (!iid.equals(Ci.nsIFactory))
  1000.       throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  1001.     
  1002.     if (cid.equals(FW_CLASSID))
  1003.       return new GenericComponentFactory(FeedWriter);
  1004.       
  1005.     throw Cr.NS_ERROR_NO_INTERFACE;
  1006.   },
  1007.   
  1008.   registerSelf: function M_registerSelf(cm, file, location, type) {
  1009.     var cr = cm.QueryInterface(Ci.nsIComponentRegistrar);
  1010.     
  1011.     cr.registerFactoryLocation(FW_CLASSID, FW_CLASSNAME, FW_CONTRACTID,
  1012.                                file, location, type);
  1013.     
  1014.     var catman = 
  1015.         Cc["@mozilla.org/categorymanager;1"].
  1016.         getService(Ci.nsICategoryManager);
  1017.     catman.addCategoryEntry("JavaScript global constructor",
  1018.                             "BrowserFeedWriter", FW_CONTRACTID, true, true);
  1019.   },
  1020.   
  1021.   unregisterSelf: function M_unregisterSelf(cm, location, type) {
  1022.     var cr = cm.QueryInterface(Ci.nsIComponentRegistrar);
  1023.     cr.unregisterFactoryLocation(FW_CLASSID, location);
  1024.   },
  1025.   
  1026.   canUnload: function M_canUnload(cm) {
  1027.     return true;
  1028.   }
  1029. };
  1030.  
  1031. function NSGetModule(cm, file) {
  1032.   return Module;
  1033. }
  1034.  
  1035. //@line 44 "/build/buildd/firefox-2.0.0.3+1/browser/components/feeds/src/../../../../toolkit/content/debug.js"
  1036.  
  1037. var gTraceOnAssert = true;
  1038.  
  1039. /**
  1040.  * This function provides a simple assertion function for JavaScript.
  1041.  * If the condition is true, this function will do nothing.  If the
  1042.  * condition is false, then the message will be printed to the console
  1043.  * and an alert will appear showing a stack trace, so that the (alpha
  1044.  * or nightly) user can file a bug containing it.  For future enhancements, 
  1045.  * see bugs 330077 and 330078.
  1046.  *
  1047.  * To suppress the dialogs, you can run with the environment variable
  1048.  * XUL_ASSERT_PROMPT set to 0 (if unset, this defaults to 1).
  1049.  *
  1050.  * @param condition represents the condition that we're asserting to be
  1051.  *                  true when we call this function--should be
  1052.  *                  something that can be evaluated as a boolean.
  1053.  * @param message   a string to be displayed upon failure of the assertion
  1054.  */
  1055.  
  1056. function NS_ASSERT(condition, message) {
  1057.   if (condition)
  1058.     return;
  1059.  
  1060.   var assertionText = "ASSERT: " + message + "\n";
  1061.  
  1062. //@line 72 "/build/buildd/firefox-2.0.0.3+1/browser/components/feeds/src/../../../../toolkit/content/debug.js"
  1063.   Components.util.reportError(assertionText);
  1064.   return;
  1065. //@line 108 "/build/buildd/firefox-2.0.0.3+1/browser/components/feeds/src/../../../../toolkit/content/debug.js"
  1066. }
  1067. //@line 37 "/build/buildd/firefox-2.0.0.3+1/browser/components/feeds/src/GenericFactory.js"
  1068.  
  1069. /**
  1070.  * An object implementing nsIFactory that can construct other objects upon
  1071.  * createInstance, passing a set of parameters to that object's constructor.
  1072.  */
  1073. function GenericComponentFactory(ctor, params) {
  1074.   this._ctor = ctor;
  1075.   this._params = params;
  1076. }
  1077. GenericComponentFactory.prototype = {
  1078.   _ctor: null,
  1079.   _params: null,
  1080.   
  1081.   createInstance: function GCF_createInstance(outer, iid) {
  1082.     if (outer != null)
  1083.       throw Cr.NS_ERROR_NO_AGGREGATION;
  1084.     return (new this._ctor(this._params)).QueryInterface(iid);
  1085.   },
  1086.   
  1087.   QueryInterface: function GCF_QueryInterface(iid) {
  1088.     if (iid.equals(Ci.nsIFactory) ||
  1089.         iid.equals(Ci.nsISupports)) 
  1090.       return this;
  1091.     throw Cr.NS_ERROR_NO_INTERFACE;
  1092.   }
  1093. };
  1094.  
  1095.